import axios, {AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig} from "axios";
import {useUserStore} from "@/store/modules/user";

import {ElMessage} from "element-plus";

const instance = axios.create({
    baseURL: '',
    timeout: 50000
})
// 添加请求拦截器
instance.interceptors.request.use(function (config){
    const url = `${import.meta.env.VITE_API_BASE_PATH}${config.url}`
    // 设置请求头
    setRequestHeader(config)
    return {
        ...config,
        url,
    };
}, function (error){
    return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(function (response){
    // if(response.data.errmsg === 'token error'){
    //     ElMessage.error({message: "token非法"})
    // }
    return response;
}, function (error){
    // 获取错误提示
    const msg = error.response?.data?.msg
    console.log(msg)
    switch (msg){
        // 账户锁定
        case '账号已被禁用':
            const userStore = useUserStore()
            userStore.reset()
            ElMessage.error(msg)
            return Promise.reject(error)
    }
    ElMessage.error(msg || '请求错误，请重试')
    return Promise.reject(error)
})
export interface Data{
    [index: string]: unknown
}
interface Http{
    get: <T>(url: string, data: any, config?: AxiosRequestConfig) => Promise<AxiosResponse<IResponse<T>>>
    file: <T>(url: string, data: any, config?: AxiosRequestConfig) => Promise<AxiosResponse<IResponse<T>>>
    post: <T>(url: string, data: any, config?: AxiosRequestConfig) => Promise<AxiosResponse<IResponse<T>>>
    put: <T>(url: string, data: any, config?: AxiosRequestConfig) => Promise<AxiosResponse<IResponse<T>>>
    patch: <T>(url: string, data: any, config?: AxiosRequestConfig) => Promise<AxiosResponse<IResponse<T>>>
    delete: <T>(url: string, data: any, config?: AxiosRequestConfig) => Promise<AxiosResponse<IResponse<T>>>
}
const http: Http = {
    get(url, data, config){
        return instance.get(url, {
            params: data,
            ...config
        })
    },
    post(url, data, config){
        return instance.post(url, data, config)
    },
    file(url, data, config){
        return instance.postForm(url, data, {
            ...config,
        })
    },
    put(url, data, config){
        return instance.put(url, data, config)
    },
    patch(url, data, config){
        return instance.patch(url, data, config)
    },
    delete(url, data, config){
        return instance.delete(url, {
            data,
            ...config
        })
    }
}
/**
 * 设置请求头
 * @param config axios配置对象
 */
const setRequestHeader = (config: InternalAxiosRequestConfig<any>) => {
    // 用户登录后接口都需要额外追加参数
    const {getToken} = useUserStore()
    // 用户登录后需要进行数据加密
    if(getToken){
        config.headers.set('x-token', getToken, false)
    }
    // 设置请求头内容
}
export default http